package uit.comstore.model.blo;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import uit.comstore.model.entity.Manufacturer;
import uit.comstore.utils.HibernateSessionFactory;

public class ManufacturerBLO {
	@SuppressWarnings("unchecked")
	public List<Manufacturer> list() {
		List<Manufacturer> manufacturers = null;
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();	
		session.beginTransaction();
		Query query = session.createQuery("from Manufacturer");
		manufacturers = query.list();
		session.getTransaction().commit();
		return manufacturers;
	}
	
	public Manufacturer getById(Long id){
		Manufacturer manufacturer = null;
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();	
		session.beginTransaction();
		manufacturer = (Manufacturer) session.get(Manufacturer.class, id);
		session.getTransaction().commit();
		return manufacturer;
	}
	
	public Manufacturer add(Manufacturer manufacturer) {
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(manufacturer);
		session.getTransaction().commit();
		return manufacturer;
	}
	
	public Manufacturer delete(Long id) {
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Manufacturer manufacturer = (Manufacturer) session.load(Manufacturer.class, id);
		if(null != manufacturer) {
            session.delete(manufacturer);
        }
		session.getTransaction().commit();
		return manufacturer;
	}
	
	public Manufacturer update(Manufacturer mf){
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Manufacturer manufacturer = (Manufacturer)session.get(Manufacturer.class, mf.getId());
		manufacturer.setName(mf.getName());
		manufacturer.setUrl(mf.getUrl());
		manufacturer.setImage(mf.getImage());
		session.update(manufacturer);
		session.getTransaction().commit();
		session.close();
		return manufacturer;
	}
}
